<template>
  <div class="content">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header content="详情" @back="goback"></el-page-header>
        <div class="card-box--setbtn" v-if="isEdit">
          <el-button @click="goback">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </div>
      </div>
    </el-card>
    <el-card class="card-box form-box">
      <div>
        <el-form
          ref="formRef"
          @submit.prevent
          :model="formState"
          :rules="Rules"
          label-width="120px"
          :disabled="!isEdit"
        >
          <!-- <el-form-item
            label="标题"
            placeholder="请输入标题名称"
            prop="title"
          >
            <el-input
              v-model="formState.title"
              class="width-custom220"
              
            />
          </el-form-item> -->

          <el-form-item label="标题" placeholder="请输入标题" prop="title">
            <el-input v-model="formState.title" class="width-custom220" />
          </el-form-item>
          <!-- <el-form-item label="文档权限" prop="projectPhaseName">
            <el-input
              v-model="formState.documentName"
              class="width-custom220"
              
            />
          </el-form-item> -->
          <el-form-item label="公开范围">
            <el-radio-group v-model="publicScope" @change="handleChangePublic">
              <el-radio :label="2">全部公开</el-radio>
              <el-radio :label="3">项目组内公开</el-radio>
              <el-radio :label="1">选定人员公开</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" v-if="publicScope === 3">
            <span>选择项目组：</span>
            <!-- <el-select v-model="formState.documentName">
              <el-option
                v-for="item in [1, 2, 3]"
                :label="item"
                :key="item"
                :value="item"
              ></el-option>
            </el-select> -->
            <el-select
              v-model="publicIds"
              clearable
              multiple
              filterable
              value-key="id"
              placeholder="请选择"
              @change="handlePublicProject"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.projectName"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" v-if="publicScope === 1">
            <span>选择成员：</span>
            <el-select
              v-model="publicIds"
              clearable
              filterable
              remote
              multiple
              value-key="id"
              placeholder="请输入姓名搜索"
              :remote-method="query => getTableLeaderData(query, 'public')"
              @change="handlePublicUser"
            >
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.name"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="下载权限">
            <el-radio-group
              v-model="dowloadScope"
              @change="handleChangeDownload"
            >
              <el-radio :label="2">所有人可下载</el-radio>
              <el-radio :label="3">项目组成员可下载</el-radio>
              <el-radio :label="1">选定人员可下载</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" v-if="dowloadScope === 3">
            <span>选择项目组：</span>
            <el-select
              v-model="dowloadIds"
              clearable
              multiple
              filterable
              value-key="id"
              placeholder="请选择"
              @change="handleDownLoadProject"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.projectName"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" v-if="dowloadScope === 1">
            <span>选择成员：</span>
            <el-select
              v-model="dowloadIds"
              clearable
              filterable
              remote
              multiple
              value-key="id"
              placeholder="请输入姓名搜索"
              :remote-method="query => getTableLeaderData(query, 'down')"
              @change="handleDownLoadUser"
            >
              <el-option
                v-for="item in downUserList"
                :key="item.id"
                :label="item.name"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-row>
            <el-col>
              <el-form-item label="上传文档" prop="attachment">
                <ecm-upload
                  :files="defaultFileList"
                  :docid="docid"
                  @setFile="handleSuccess"
                ></ecm-upload>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="内容摘要" prop="summary">
            <el-input
              v-model="formState.summary"
              :autosize="{ minRows: 2, maxRows: 6 }"
              type="textarea"
            ></el-input>
          </el-form-item>
          <el-form-item label="参与人员" prop="attendMenber">
            <el-input
              v-model="formState.attendMenber"
              :row="3"
              type="textarea"
            ></el-input>
          </el-form-item>
          <el-form-item label="参与单位" prop="attendDept">
            <el-input
              v-model="formState.attendDept"
              :row="3"
              type="textarea"
            ></el-input>
          </el-form-item>
          <el-form-item label="交流时间" prop="occurrenceTime">
            <el-date-picker
              v-model="formState.occurrenceTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import NotifMessage from "/@/utils/message/notification";
import * as api from "/@/api/communicate";
import { postProjectList2 } from "/@/api/project";
import { getUsersForScience } from "/@/api/user";
import { storageLocal } from "/@/utils/storage";
import EcmUpload from "/@/components/ecmUpload/index.vue";

const formRef = ref<HTMLFormElement | null>(null) as any;

const router = useRouter();
const route = useRoute();
let docid = window["ecmDocType"].communication;
let publicScope = ref(2);
let publicIds = ref([]);

let dowloadScope = ref(2);
let dowloadIds = ref([]);

let projectList = ref([]);
let userList = ref([]);
let downUserList = ref([]);

const formState = reactive({
  title: "",
  summary: "",
  attendMenber: "",
  attendDept: "",
  attachmentArr: [],
  occurrenceTime: "",
  authItems: []
});

// {
//  itemId:"",
//  itemType:"",
//  operType:"",
// }

const Rules = {
  title: [{ required: true, message: "请输入名称", trigger: "blur" }],
  summary: [{ required: true, message: "请输入摘要", trigger: "change" }],
  attendMenber: [
    { required: true, message: "请输入参与人员", trigger: "change" }
  ],
  attendDept: [
    { required: true, message: "请输入参与单位", trigger: "change" }
  ],
  attachmentArr: [{ required: true, message: "请上传文档", trigger: "change" }],
  occurrenceTime: [{ required: true, message: "请选择时间", trigger: "change" }]
};

let isEdit = computed(() => {
  // @ts-ignore
  if (["add", "edit"].includes(route.query.mode)) {
    return true;
  } else {
    return false;
  }
});

/* 上传 -- start */
let defaultFileList = ref([]);

const handleSuccess = res => {
  defaultFileList.value = res.file;
  formState.attachmentArr = res.file;
  formRef.value.clearValidate();
};
/* 上传 -- end */

const handleChangePublic = event => {
  console.log(event, "event");
  publicIds.value = [];
  formState.authItems = formState.authItems.filter(item => {
    return item?.operType !== "R";
  });
  if (event === 1) {
    const info = storageLocal.getItem("rdms-info");
    publicIds.value.push({
      id: info.userId,
      name: info.name
    });
    formState.authItems.push({
      itemId: info.userId,
      itemType: event,
      operType: "R",
      itemName: info.name
    });
    if (userList.value.findIndex(el => el.id === info.userId) === -1) {
      userList.value.push({
        id: info.userId,
        name: info.name
      });
    }
  }
};

const handlePublicProject = item => {
  console.log(item);

  const newAuthItems = [];
  publicIds.value.forEach(i => {
    const project = projectList.value.find(el => el.id === i.id);
    newAuthItems.push({
      itemId: i.id,
      itemType: publicScope.value,
      operType: "R",
      itemName: project.projectName
    });
  });
  formState.authItems = formState.authItems.filter(i => {
    return i.operType === "D";
  });

  formState.authItems = formState.authItems.concat(newAuthItems);
  formState.authItems = uniqWith(formState.authItems);
};

const handlePublicUser = item => {
  console.log(item);

  const newAuthItems = [];
  publicIds.value.forEach(i => {
    newAuthItems.push({
      itemId: i.id,
      itemType: publicScope.value,
      operType: "R",
      itemName: i.name
    });
    if (userList.value.findIndex(el => el.id === i.id) === -1) {
      userList.value.push({
        id: i.id,
        name: i.name
      });
    }
  });
  formState.authItems = formState.authItems.filter(i => {
    return i.operType === "D";
  });

  formState.authItems = formState.authItems.concat(newAuthItems);
  formState.authItems = uniqWith(formState.authItems);
};

const handleChangeDownload = event => {
  console.log(event, "event");
  dowloadIds.value = [];
  formState.authItems = formState.authItems.filter(item => {
    return item?.operType !== "D";
  });
  if (event === 1) {
    const info = storageLocal.getItem("rdms-info");
    dowloadIds.value.push({
      id: info.userId,
      name: info.name
    });
    formState.authItems.push({
      itemId: info.userId,
      itemType: event,
      operType: "D",
      itemName: info.name
    });
    if (downUserList.value.findIndex(el => el.id === info.userId) === -1) {
      downUserList.value.push({
        id: info.userId,
        name: info.name
      });
    }
  }
};

const handleDownLoadProject = item => {
  console.log(item);
  const newAuthItems = [];
  dowloadIds.value.forEach(i => {
    const project = projectList.value.find(el => el.id === i.id);
    newAuthItems.push({
      itemId: i.id,
      itemType: dowloadScope.value,
      operType: "D",
      itemName: project.projectName
    });
  });
  formState.authItems = formState.authItems.filter(i => {
    return i.operType === "R";
  });

  formState.authItems = formState.authItems.concat(newAuthItems);
  formState.authItems = uniqWith(formState.authItems);
};

const handleDownLoadUser = item => {
  console.log(item);
  const newAuthItems = [];
  dowloadIds.value.forEach(i => {
    newAuthItems.push({
      itemId: i.id,
      itemType: dowloadScope.value,
      operType: "D",
      itemName: i.name
    });
    if (downUserList.value.findIndex(el => el.id === i.id) === -1) {
      downUserList.value.push({
        id: i.id,
        name: i.name
      });
    }
  });
  formState.authItems = formState.authItems.filter(i => {
    return i.operType === "R";
  });

  formState.authItems = formState.authItems.concat(newAuthItems);
  formState.authItems = uniqWith(formState.authItems);
};

// 去重
function uniqWith(arr) {
  // 缓存用于记录
  const cache = [];
  for (const t of arr) {
    // 检查缓存中是否已经存在
    if (cache.find(c => c.itemId === t.itemId && c.operType === t.operType)) {
      // 已经存在说明以前记录过，现在这个就是多余的，直接忽略
      continue;
    }
    // 不存在就说明以前没遇到过，把它记录下来
    cache.push(t);
  }
  // 记录结果就是过滤后的结果
  return cache;
}

const goback = () => {
  router.push("/communication/manage");
};

const getDetail = async () => {
  const params = {
    id: route.query.id
  };
  const { code, data } = await api.postCommunicateInfo(params);

  if (code === 200) {
    const {
      // createTime,
      // createUserName,
      // billNum,
      title,
      summary,
      attendMenber,
      attendDept,
      attachmentArr,
      occurrenceTime,
      authItems
    } = data;

    // infoState.createTime = createTime;
    // infoState.createUserName = createUserName;
    // infoState.billNum = billNum;

    formState.title = title;
    formState.summary = summary;
    formState.attendMenber = attendMenber;
    formState.attendDept = attendDept;
    formState.occurrenceTime = occurrenceTime;
    attachmentArr.map(el => {
      el["name"] = el.fileName;
    });
    formState.attachmentArr = attachmentArr;
    defaultFileList.value = attachmentArr;

    formState.authItems = authItems;
    authItems.forEach(item => {
      if (item.operType === "R" && item.itemType == "1") {
        publicScope.value = 1;
      } else if (item.operType === "R" && item.itemType == "3") {
        publicScope.value = 3;
      } else if (item.operType === "D" && item.itemType == "1") {
        dowloadScope.value = 1;
      } else if (item.operType === "D" && item.itemType == "3") {
        dowloadScope.value = 3;
      }
    });

    const pub = authItems.filter(item => {
      return item.operType === "R";
    });
    pub.map(i => {
      publicIds.value.push({
        id: +i.itemId,
        name: i.itemName
      });
      // if (projectList.value.findIndex(el => el.id === +i.itemId) === -1) {
      //   projectList.value.push({ id: +i.itemId, projectName: i.itemName });
      // }
      if (publicScope.value === 3) {
        if (projectList.value.findIndex(el => el.id === +i.itemId) === -1) {
          projectList.value.push({
            id: +i.itemId,
            projectName: i.itemName
          });
        }
      } else if (publicScope.value === 1) {
        if (userList.value.findIndex(el => el.id === +i.itemId) === -1) {
          userList.value.push({
            id: +i.itemId,
            name: i.itemName
          });
        }
      }
    });

    const dow = authItems.filter(item => {
      return item.operType === "D";
    });
    dow.map(i => {
      dowloadIds.value.push({
        id: +i.itemId,
        name: i.itemName
      });
      // if (projectList.value.findIndex(el => el.id === +i.itemId) === -1) {
      //   projectList.value.push({ id: +i.itemId, projectName: i.itemName });
      // }
      if (dowloadScope.value === 3) {
        if (projectList.value.findIndex(el => el.id === +i.itemId) === -1) {
          projectList.value.push({
            id: +i.itemId,
            projectName: i.itemName
          });
        }
      } else if (dowloadScope.value === 1) {
        if (downUserList.value.findIndex(el => el.id === +i.itemId) === -1) {
          downUserList.value.push({
            id: +i.itemId,
            name: i.itemName
          });
        }
      }
    });
  }
};
const handleSubmit = async () => {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      const copyFormData = JSON.parse(JSON.stringify(formState));
      if (route.query.mode === "add") {
        const { code, message } = await api.postCommunicateAdd(copyFormData);
        if (code === 200) {
          NotifMessage.success("保存成功");
          goback();
        } else {
          NotifMessage.error(message);
        }
      } else {
        const { code, message } = await api.postCommunicateUpdate(
          Object.assign(copyFormData, { id: route.query.id })
        );
        if (code === 200) {
          NotifMessage.success("修改成功");
          goback();
        } else {
          NotifMessage.error(message);
        }
      }
    } else {
      return false;
    }
  });
};
// const handleCheckChange = () => {
//   const res = projectTreeRef.value.getCurrentNode();
//   formState.projectName = [res][0].projectName;
//   formState.projectManageId = [res][0].id;
//   projectRef.value.blur();
// };

// 获取项目信息
const getProjectList = async () => {
  try {
    const { code, data } = await postProjectList2({
      pageNum: 1,
      pageSize: 0
    });
    if (code === 200) {
      projectList.value = data.list;
    }
  } catch (err) {
    console.log(err);
  }
};

async function getTableLeaderData(query = "", type) {
  try {
    const params = {
      pageNum: 1,
      pageSize: 200,
      nameLike: query
    };
    const { code, data } = await getUsersForScience(params);
    if (code === 200) {
      if (type === "public") {
        userList.value = data.list.map(item => {
          return {
            id: item.id,
            name: item.name + (item.deptName ? "-" + item.deptName : "-无")
          };
        });
      } else if (type === "down") {
        downUserList.value = data.list.map(item => {
          return {
            id: item.id,
            name: item.name + (item.deptName ? "-" + item.deptName : "-无")
          };
        });
      }
    }
  } catch (err) {
    console.log(err);
  }
}

// 文档类型
// const initDoucumentTypeList = async () => {
//   try {
//     const params = {
//       dicType: "sys_document_type"
//     };
//     const { code, data } = await postDictList(params);
//     if (code === 200) {
//       documentTypeList.value = data;
//     }
//     // console.log(code, data);
//   } catch (err) {
//     console.log(err);
//   }
// };

// 项目阶段
// const initProjectPhaseList = async () => {
//   try {
//     const params = {
//       dicType: "rd_project_stage"
//     };
//     const { code, data } = await postDictList(params);
//     if (code === 200) {
//       projectPhaseList.value = data;
//     }
//   } catch (err) {
//     console.log(err);
//   }
// };

// initDoucumentTypeList();
// initProjectPhaseList();
onMounted(async () => {
  await getProjectList();
  if (route.query.mode !== "add") {
    getDetail();
  }
});
</script>

<style lang="scss" scoped>
.content {
  :deep .el-page-header__content {
    font-size: 16px;
  }

  .card-box {
    margin-bottom: 10px;

    &--headerwrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    &--setbtn {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      width: 140px;
    }
  }

  .header__wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.form-box {
  margin-top: 10px;
}

.form-info {
  margin-bottom: 20px;
}

.header-btns {
  text-align: right;
}
</style>
